package com.wjr.braveheart.http.oldversion;

import android.content.Context;
import android.os.Handler;
import android.util.Log;

import com.wjr.braveheart.http.okhttp.OkHttpClientUtils;
import com.wjr.braveheart.http.ParamsUtils;
import com.wjr.braveheart.http.callback.EngineCallback;

import java.io.IOException;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Dispatcher;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by adminWJR on 2018/1/4.
 * OkHttp默认引擎
 * 问题：
 * 1.请求参数，很多但是有些是公用的
 * 2.每次回调都要用Json转换，但是不能够直接使用泛型
 * 3.数据库的问题，缓存 新闻类特有效果，第三方的数据库都是缓存在data/data/xxx/database
 */

public class OkHttpEngine implements IHttpEngine {

    private static OkHttpClient sOkHttpClient = OkHttpClientUtils.getOkHttpClient();
    private static Handler sHandler = new Handler();

    @Override
    public void get(Context context, String url,
                    Map<String, Object> params,
                    final EngineCallback callback) {
        final String jointUrl = ParamsUtils.appendParams(url, params);
        Log.v("OkHttpEngine->Get", jointUrl);
        Request request = new Request.Builder()
                .url(jointUrl)
                .tag(context)
                .build();
        sOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                if (call.isCanceled()) {
                    Log.v("OkHttpEngine", "onFailure: " + "请求被取消");
                    return;
                }

                sHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        callback.onError(e);
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (call.isCanceled()) {
                    Log.v("OkHttpEngine", "onResponse:" + "请求被取消");
                    return;
                }

                final String result = response.body().string();
                Log.v("OkHttpEngine->Get", "result: " + result);
                sHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        callback.onSuccess(result);
                    }
                });
            }
        });
    }

    @Override
    public void post(Context context, String url,
                     Map<String, Object> params,
                     final EngineCallback callback) {
        final String jointUrl = ParamsUtils.appendParams(url, params);
        Log.v("OkHttpEngine->Post", jointUrl);
        RequestBody requestBody = ParamsUtils.appendBody(params);
        Request request = new Request.Builder()
                .url(url)
                .tag(context)
                .post(requestBody)
                .build();
        sOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                sHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        callback.onError(e);
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String result = response.body().string();
                Log.v("OkHttpEngine->Post", "result: " + result);
                sHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        callback.onSuccess(result);
                    }
                });
            }
        });
    }

    /**
     * 取消网络请求
     *
     * @param tag 标记
     */
    @Override
    public void cancel(Context tag) {
        Dispatcher dispatcher = sOkHttpClient.dispatcher();
        synchronized (dispatcher) {
            for (Call call : dispatcher.queuedCalls()) {
                if (tag.equals(call.request().tag())) {
                    call.cancel();
                }
            }
            for (Call call : dispatcher.runningCalls()) {
                if (tag.equals(call.request().tag())) {
                    call.cancel();
                }

            }
        }
    }

}


